/**
 * Created by gli on 2015/3/31.
 */
var isChrome = false;
if (window.MessageEvent && !document.getBoxObjectFor) {
  var match = navigator.userAgent.toLowerCase().match(/chrome\/([\d.]+)/);
  isChrome = match ? match[1] : false;
}
function fixOptionText(text) {
  if (isChrome) {
    text = $.trim(text);
    var len = text.length;
    if (len == 0) return '';

    if (len > 11) {
      text = text.substr(0, 11) + '...';
    }
    return text;
  }
  return text;
}

(function( $ ) {
  'use strict'

  window.console = window.console || (function(){
    var c = {}; c.log = c.warn = c.debug = c.info = c.error = c.time = c.dir = c.profile
      = c.clear = c.exception = c.trace = c.assert = function(){};
    return c;
  })();

  var Views = {
    SURVEY_TYPES: {
      'MICRO': 1,
      'SINGLE': 2,
      'PROMOTION': 3
    },
    QUESTION_TYPES: {
      '1': 'SingleChoice',
      '2': 'MultipleChoice',
      '3': 'SingleImageChoice',
      '4': 'MultipleImageChoice',
      '5': 'SingleLine',
      '6': 'MultipleLine',
      '7': 'MultipleInput',
      '8': 'Sorting',
      '9': 'Scoring',
      '10': 'SingleVote',
      '11': 'MultipleVote',
      '12': 'SingleImageVote',
      '13': 'MultipleImageVote',
      '14': 'Promotion'
    },

    ERROR_CODES: {
      REQUIRED: 1,
      INVALID_CHAR: 2,
      COUNT_NOT_MATCH: 3
    },
    getRandomId: function() {
      return 'temp-' + new Date().getTime() + '-' + Math.floor(Math.random() * 1000);
    }
  };

  // Model
  var SurveyModel = Backbone.Model.extend({

    urlRoot : '/survey',

    defaults: {
      title: '',
      description: '',
      predefined_value: '',
      required: 0,
      other: 0,
      fields: []
    },
    
    initialize: function(options) {	
    },

    parse: function(response, options) {
      //if (response && response.fields) {
      //  var removingIndex = -1;
      //  _.each(response.fields, function(field, idx){
      //    if (field.other == 1) {
      //      removingIndex = idx;
      //    }
      //  });
      //  if (removingIndex >= 0) {
      //    delete response.fields[removingIndex];
      //  }
      //}
      return response;
    },

    setValues: function(values) {
      var fields = [];
      if (_.isArray(values)) {
        _.each(values, function(value, idx){
          if (value) {
            var field = {
              id: Views.getRandomId(),
              title: value.substr(0, 255),
              checked: 0,
              score: 0
            };
            fields.push(field);
          }
        });
      }
      if (fields.length == 0) {
        fields.push({
          title: '',
          checked: 0
        });
      }
      this.set('fields', fields, {from: 'batch'});
    }
  });

  // Collection
  var SurveyCollection = Backbone.Collection.extend({
    url: '/survey/admin/view.do',
    model: SurveyModel,
    initialize: function(models, options) {
      this.title = options.title;
      this.description = options.description;
      this.type = options.type ? options.type : 0;
      this.is_score = options.is_score ? options.is_score : 0;
      this.is_result = options.is_result ? options.is_result : 1;
    },

    getData: function() {
      var data = {
        title: this.title,
        description: this.description,
        type: this.type ? this.type : 0,
        is_score : this.is_score ? this.is_score : 0,
        is_result : this.is_result ? this.is_result : 1,
        models: this.toJSON()
      };
      return data;
    }
  });

  // defined base view
  Views.ViewBase = Backbone.View.extend({
    viewClassName: 'ViewBase',
    defaults: {
      templateId: '#noop-template'
    },
    initialize: function(options) {
      var opts = _.extend({}, this.defaults, options);
      this._templateId = opts.templateId;
      this._parent = opts.parent;
    },
    render: function() {
      var template = _.template(this.getTemplateText());
      var html = template(this.model.toJSON());
      this.$el.html(html);

      return this;
    },
    getTemplateText: function(templateId) {
      var $template = templateId ? $(templateId) : $(this._templateId);
      if ($template.length == 0) {
        console.log('No template found for ' + (templateId ? templateId : this._templateId));
        return '';
      }

      return $template.html();
    },
    update: function() {},
    isValidText: function(text) {
      var reg = /[<>\/%!=]/;
      return !reg.test(text);
    },
    validate: function() {
      return true;
    },
    getData: function() {},
    refresh: function() {},
    didInsertElement: function() {},
    destroy: function() {
      this.remove();
    }
  });

  /////////////////////////////////////////////////////////////////////////////////////////////////
  Views.TypeView = Views.ViewBase.extend({

    viewClassName: 'TypeView',
    className: 'row-item question',
    defaults: {
      baseTemplateId: '#question-template',
      popupClass: 'multiple',
      type: 1,
      active: true,
      readonly: false,
      sortable: true,
      copyEnabled: true,
      topVote: 0,
      selectedTopVote: 0,
      onRemoveOption: null,
      minOptions: 2
    },
    initialize: function(options) {
      var opts = _.extend({}, this.defaults, options);

      this._baseTemplateId = opts.baseTemplateId;
      this._type = opts.type;
      this._popupClass = opts.popupClass;
      this._active = opts.active;
      this._readonly = opts.readonly;
      this._sortable = opts.sortable;
      this._copyEnabled = opts.copyEnabled;
      this._topVote = opts.topVote;
      this._selectedTopVote = opts.selectedTopVote;
      this._onRemoveOption = opts.onRemoveOption;
      this._minOptions = opts.minOptions;

      this.$createContainer = $(opts.createContainer);
      this.$previewContiner = $(opts.previewContainer);

      this._parent = opts.parent;

      this._id = new Date().getTime() + '-' + Math.floor(Math.random() * 1000);

      ///this.bind('data-update', this.dataUpdate);

      if (!this.model) {
        var defaultData = this.getDefaultData();
        this.model = new SurveyModel(defaultData);
      }

      this.listenTo(this.model, 'change', this.dataUpdate);

      this.bind('selected', this.selected);
      this.bind('copy', this.copyView);
      this.bind('delete', this.deleteView);

      this.bind('error', this.handleError);

      this.bind('option:add', this.handleAddOption);
      this.bind('option:remove', this.handleRemoveOption);

      this.bind('input:update', this.inputUpdated);
    },

    _render: function() {
      var template = _.template(this.getTemplateText(this._baseTemplateId));
      var data = this.model.toJSON();
      data.readonly = !!this._readonly;
      var html = template(data);

      this.$el.html(html);

      this.$('.popbox').addClass(this._popupClass);
    },

    render: function(index) {
      var self = this;

      this._render();

      var typeName = this.getTypeName();

      var createViewClass = Views[typeName + 'CreateView'];
      var previewViewClass = Views[typeName + 'PreviewView'];
      if (!createViewClass) {
        throw typeName + 'CreateView Not defined';
      }
      if (!previewViewClass) {
        throw typeName + 'PreviewView Not defined';
      }

      //var options = _.extend({}, defaultData, {'parent': this});
      var createView = new createViewClass({
        model: this.model,
        parent: this,
        readonly: this._readonly,
        onRemoveOption: this._onRemoveOption,
        minOptions: this._minOptions
      });
      var previewView = new previewViewClass({
        model: this.model,
        parent: this,
        readonly: this._readonly,
        sortable: this._sortable,
        copyEnabled: this._copyEnabled,
        topVote: this._topVote,
        selectedTopVote: this._selectedTopVote
      });

      createView.render();
      previewView.render();

      this.$createView = createView;
      this.$previewView = previewView;

      this.$('.popbox').html(this.$createView.el);
      this.$('.preview').html(previewView.el);

      if (this._active && !this._readonly) this.$el.addClass('active');

      setTimeout(function() {
        self._updateNarrPosition();
      }, 500);

      return this;
    },

    getTypeName: function() {
      return Views.QUESTION_TYPES[this._type];
    },
    getRandomId: function() {
      return Views.getRandomId();
    },
    getDefaultData: function() {
      return {};
    },

    validate: function() {
      return this.$createView.validate();
    },

    getData: function() {
      var viewData = {};
      if (this.model) {
        viewData = this.model.toJSON();
        if ($.trim(viewData.title).length == 0) viewData.title = '未命名';
        if (viewData && viewData.fields) {
          var removingIndex = -1;
          _.each(viewData.fields, function(field, idx) {
            if (field.other == 1) {
              removingIndex = idx;
            }
            if ($.trim(field.title).length == 0) field.title = '选项';
          });
          if (removingIndex >= 0) {
            viewData.fields.splice(removingIndex, 1);
          }
        }
      }
      return viewData;
    },

    dataUpdate: function(model, opts) {
      var self = this;

      this.$previewView.trigger('refresh', model);

      if (opts.from == 'batch') {
        // update create view
        this.$createView.trigger('refresh', model, opts.from);
      }

      self._updateNarrPosition();

    },

    _updateNarrPosition: function() {
      var originalTop = parseInt(this.$('.popbox').css('top'));
      var newTop = this.$el.outerHeight() / 2 - originalTop - 5;
      this.$('.narr').animate({'top': newTop}, 200);
    },

    inputUpdated: function(view) {
      if (this._parent) this._parent.inputUpdated(this, view);
    },

    selected: function(view) {
      if (this._parent) {
        var result = this._parent.selected(this);
        if (result === false) return;
      }
      if (view) {
        var $item = view.$el.closest('.row-item');
        $item.siblings().removeClass('active').end().addClass('active');
      } else {
        this.$el.addClass('active');
      }

      var views = this._parent.getViews();
      if (views.indexOf(this) == views.length - 1) {
        // hide the relationship checkbox
        this.$('input:checkbox[name=relationship]').prop('checked', false).parent().hide();
        this.$('.relationship-add').closest('.choice_box').hide();
        this.model.set('relationship', 0, {silent: true});
      } else {
        this.$('input:checkbox[name=relationship]').parent().show();
      }
    },

    unselect: function(view) {
      this.$el.removeClass('active');
    },

    preview: function() {
      return this.$previewView.el;
    },

    copyView: function() {
      if (this._parent) {
        this._parent.copyView(this);
      }
    },

    deleteView: function() {
      //this.$previewView.remove();
      //this.$createView.remove();

      // check if the view related
      var isRelated = false;
      if(this._parent.isRelated(this)) {
        if (!confirm('删除该问题将取消关联，确定？')) {
          return;
        }
        isRelated = true;
      }

      // if deleting view is last, should clear the relations of the previous view
      var views = this._parent.getViews();
      if (views.indexOf(this) != -1 && views.indexOf(this) == views.length - 1) {
        this._parent.clearRelations(views.indexOf(this) - 1);
      }

      this.remove();
      if (this.model) {
        this.stopListening(this.model);
        //this.model.destroy();
        //if (this._parent) this._parent.removeModel(this.model);
        if (this._parent) this._parent.removeView(this);
      }

      if (isRelated) this._parent.updateRelatedOptions();

    },

    handleError: function(code, element, view, message) {
      if (this._parent) this._parent.handleError(code, element, view, message);
    },

    handleAddOption: function(view) {
      console.log('handleAddOption', view);
      if (this._parent) this._parent.handleAddOption(view);

      if (this.model.get('type') == 1 || this.model.get('type') == 3) this.$createView.updateRelationView(true);
//      alignH();
    },

    handleRemoveOption: function(view) {
      console.log('handleRemoveOption', view);
      if (this._parent) this._parent.handleRemoveOption(view);
//      alignH();
    },

    isRelated: function(modelIndex) {
      var result = false;
      if (this.$createView.model.has('relations')) {
        var relations = this.$createView.model.get('relations');
        _.each(relations, function(relation, idx) {
          if (relation.modelId == modelIndex) {
            result = true;
          }
        });
      }
      return result;
    },

    hasRelated: function() {
      if (this.model.has('relations')) {
        return this.model.get('relations').length > 0;
      }
      return false;
    },

    updateRelatedOptions: function() {
      this.$createView.updateRelatedOptions();
    },

    cancelRelatedOptions: function() {
      this.$createView.cancelRelatedOptions();
    },

    clearRelations: function() {
      this.$createView.clearRelations();
    }

  });

  /////
  Views.DefaultCreateView = Views.ViewBase.extend({
    viewClassName: 'DefaultCreateView',
    defaults: {
      templateId: '#noop-template',
      optionTemplateId: '#noop-template',
      otherOptionTemplateId: '#other-option-template',
      relationshipOptionId: '#relationship-option-template',
      supportUpload: false,
      onRemoveOption: null,
      minOptions: 2,
      readonly: false
    },
    events: {
      'blur input:text, textarea': 'inputValidate',
      'input input:text': 'inputUpdate',
      'click .option-group a.add': 'addOption',
      'click .option-group a.delet': 'removeOption',
      'click .add-other': 'addOtherOption',
      'click .other a.delet': 'removeOtherOption',
      'click .batch-add': 'batchAdd',
      'input textarea[name=description]': 'descriptionChange',
      'change input[name=required]': 'requiredChange',
      'click .relations': 'loadRelations',
      'click .relationship-add': 'addRelationship',
      'click .relationship-delete': 'deleteRelationship',
      'change .relation1': 'relationOptionChanged',
      'change .relation2': 'relatedOptionChanged',
      'click input:checkbox[name=required]': 'requireAction',
      'click input:checkbox[name=relationship]': 'relationshipAction',
      'click .setting_menu .close': 'toggleSettingArea'
    },
    initialize: function(options) {
      Views.ViewBase.prototype.initialize.call(this, options);
      var opts = _.extend({}, this.defaults, options);
      this._templateId = opts.templateId;
      this._supportUpload = opts.supportUpload;
      this._onRemoveOption = opts.onRemoveOption;
      this._minOptions = opts.minOptions;
      this._readonly = opts.readonly;

      this._XHRs = {};

      this.bind('refresh', this.render);
    },
    render: function(obj, opt) {
      var template = _.template(this.getTemplateText());

      //  opt == 'batch', clear the fieldId in relations
      var relationAddDisabled = false;
      if (opt && opt == 'batch') {
        // clear the relations
        this.model.unset('relations', {silent: true});
      } else if (!this.model.has('relations')) {
        var relations = [];
        var fields = this.model.get('fields');
        var direct_id = this.model.get('direct_id') ? parseInt(this.model.get('direct_id'), 10) : 0;
        var collection = this._parent._parent.getCollection();
        if (!isNaN(direct_id) && direct_id) {
          relationAddDisabled = true;
          if (direct_id == -1) {
            relations.push({
              fieldId: -1,
              modelId: -1
            });
          } else {
            collection.each(function(m, index){
              if (m.get('id') == direct_id) {
                relations.push({
                  fieldId: -1,
                  modelId: index
                });
              }
            });
          }
        } else {
          _.each(fields, function(field, idx){
            if (field.related_id > 0) {
              // get index by related id
              collection.each(function(m, index) {
                if (m.get('id') == field.related_id) {
                  relations.push({
                    fieldId: field.other == 1 ? -2 : field.id,
                    modelId: index
                  });
                }
              });
            } else if (field.related_id == -1) {
              relations.push({
                fieldId: field.id,
                modelId: -1
              });
            }
          });
        }
        console.log('[DefaultCreateView render] relations:', relations);
        this.model.set('relations', relations, {silent: true});
      }
      
      var data = this.model.toJSON();
      data.minOptions = this._minOptions;
      data.survey_type = 1;
      if (typeof data.relationship == 'undefined') data.relationship = 0;
      if (this._parent && this._parent._parent && this._parent._parent.getCollection) {
        var index = this._parent._parent.getCollection().indexOf(this.model);
        if (index >= 0) {
          data.viewIndex = index + 1;
        } else {
          data.viewIndex = this._parent._parent.getCollection().length + 1;
        }

        data.survey_type = this._parent._parent.getCollection().type;

      } else {
        data.viewIndex = 1;
      }

      data.readonly = !!this._readonly;

      //data.hideSetting = !/^\d+$/.test($.trim(this.model.get('id')));
      data.relationAddDisabled = relationAddDisabled;

      var html = template(data); 
      this.$el.html(html);
      
      $(document).bind('drop dragover', function (e) {
        e.preventDefault();
      });

      this.bindSortable();

      var self = this;
      setTimeout(function() {
        self.bindUpload();

        self.loadRelations();
      }, 500);

      if (!this.model.get('id') || !/^\d+$/.test($.trim(this.model.get('id')))) {
        this.$('.setting .setting_box').hide();
        this.$('.setting_menu .close').addClass('open').find('label').html('展开');
      }

      return this;
    },
    inputValidate: function(e) {
      this._validate(e.target);
    },
    inputUpdate: function(event, reRender) {
      console.log('default input update, trigger child event');
    },
    descriptionChange: function() {
      console.log('desc changed');
      this.inputUpdate();
    },
    requiredChange: function() {
      this.inputUpdate();
    },
    addOption: function() {},
    removeOptionConfirm: function() {
      if (this._onRemoveOption && $.isFunction(this._onRemoveOption)) {
        return this._onRemoveOption.call(this, this._parent);
      }
      return true;
    },
    removeOption: function() {},
    addOtherOption: function(e) {
      if (this.model.get('other') != 1) {
        var template = _.template(this.getTemplateText(this.defaults.otherOptionTemplateId));
        var html = template();

        this.$('.option-group').after(html);

        var $target = $(e.target);
        $target.siblings('span').hide().end().hide();

        this.inputUpdate();
      }
    },
    removeOtherOption: function(e) {
      this.model.set('other', 0);
      this.render();
      this.inputUpdate(null, true);
    },
    batchAdd: function(e) {
      UIdialogNew($(e.target));
    },
    getDropZone: function() {
      return null;
    },
    bindUpload: function() {
      var self = this;
      if (this._supportUpload && this.getDropZone()) {
        var dropZone = this.getDropZone();

        var maxFiles = 5;
        this.$el.fileupload({
          url: '/core/file_uploader.do',
          dataType: 'json',
          dropZone: dropZone,
          maxNumberOfFiles: 5,
          formData: [
            {name: 'source', value: 'ajaxupload'},
            {name: 'file_field', value: 'image_upload'},
            {name: 'thumb_config', value: 'survey'},
            {name: 'mode', value: 'max'}
          ],
          add: function (e, data) {
            var randomKey = new Date().getTime() + '-' + Math.floor(Math.random() * 1000);
            data.context = self.append(data);
            data.context.data('randomKey', randomKey);
            var xhr = data.submit();
            self._XHRs[randomKey] = xhr;
          },
          progress: function(e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            data.context.find('.progress').css('width', progress + '%');
          },
          done: function (e, data) {
            self.uploaded(data);
            var randomKey = data.context.data('randomKey');
            if (randomKey) {
              delete self._XHRs[randomKey];
            }
          },
          error: function(jqXHR, textStatus, errorThrown) {
            if (errorThrown === 'abort') {
              self.uploadCancelled(jqXHR, textStatus, errorThrown);
            }
            self.uploadError(jqXHR, textStatus, errorThrown);
          },
          getNumberOfFiles: self.getNumberOfFiles
        }).bind('fileuploadadd', function(e, data) {
          var fileCount = data.files.length;
          if (fileCount > maxFiles) {
            alert('The max number of files is ' + maxFiles);
            return false;
          }
        });
      }
    },
    getNumberOfFiles: function() {
      return 1;
    },
    progress: function(data) {},
    append: function(data) {},
    uploaded: function(data) {},
    uploadCancelled: function() {},
    uploadError: function(jqXHR, textStatus, errorThrown) {},
    cancelAllUpload: function() {
      _.each(this._XHRs, function(xhr, key) {
        xhr.abort();
      });

      this._XHRs = {};
    },
    bindSortable: function() {
      var self = this;
      this.$('.option-group').sortable({
        handle: '.edit03',
        stop: function(e, ui) {
          self.sortableStop.call(self, e, ui);
        }
      });
    },
    sortableStop: function(e, ui) {
      console.log('sortable stop', ui);
      this.inputUpdate();
    },
    _validate: function(element, trigger) {
      if (element) {
        var hasError = false;
        var self = this;
        var value = $(element).val();
        var required = $(element).prop('required');
        var pattern = $(element).prop('pattern');
        if ($.trim(value).length == 0 && required) {
          hasError = true;
          $(element).addClass('invalid').next().attr('title', '必填项');
          if (trigger) self._parent.trigger('error', Views.ERROR_CODES.REQUIRED, element, self);
        } else {
          if ($.trim(value).length && pattern) {
            var regExp = new RegExp(pattern);
            var match = value.match(regExp);
            if (!match || match[0] != value) {
              hasError = true;
              //$(element).addClass('invalid').next().attr('title', '存在非法字符<>\/%!=或评分不为正整数');
              $(element).addClass('invalid').parent().find(".invalid").attr('title', '存在非法字符<>\/%!=或评分不为正整数');
              if (trigger) self._parent.trigger('error', Views.ERROR_CODES.INVALID_CHAR, element, self);
            }
          }
        }

        if (!hasError) $(element).removeClass('invalid').next().removeAttr('title');
      }
    },
    validate: function() {
      var self = this;
      this.$('input:text, textarea').each(function() {
        self._validate(this, true);
      });
    },

    loadRelations: function() {
      if (this.model.get('relations')) {
        var self = this;
        var relations = this.model.get('relations');
        _.each(relations, function(relation, idx) {
          self.addRelationshipView(relation);
        });
      }
    },
    addRelationship: function(event) {
      var views = this._parent._parent.getViews();
      var viewIndex = views.indexOf(this._parent);
      if (viewIndex == views.length - 1) {
        console.log('This view is last item, can not add the relation');
        alert('最后一题无法设置关联逻辑');
        return;
      }

      // if AnyOptions selected
      var relations = this.model.get('relations') ? this.model.get('relations') : [];
      var anyOptions = false;
      _.each(relations, function(r, idx) {
        if (r.fieldId == -1) {
          anyOptions = true;
        }
      });
      if (anyOptions) {
        return;
      }

      var relation = {};
      this.addRelationshipView(relation);
      relations.push(relation);
    },
    addRelationshipView: function(relation) {
      var template = _.template(this.getTemplateText(this.defaults.relationshipOptionId));

      var data = this.model.toJSON();
      var collection = this._parent._parent.getCollection();
      var views = this._parent._parent.getViews();
      var viewIndex = views.indexOf(this._parent);
      data.viewIndex = viewIndex;
      if (viewIndex == collection.length - 1) {
        // already last item
        return;
      } else {
        var views = this._parent._parent.getViews();
        data.views = views;
      }

      data.relation = relation ? relation : {};

      var field_ids = [];
      this.$('.relationship-group').find('.box_list .relation1').each(function() {
        if ($(this).val()) field_ids.push($(this).val());
      });

      _.each(data.fields, function(field, idx) {
        if (field.other != 1) {
          if ($.inArray(field.id, field_ids) != -1) {
            field.hide = true;
          } else {
            field.hide = false;
          }
        }
      });

      data.ooHide = false;
      if ($.inArray('-2', field_ids) != -1) { // Other-Option selected
        data.ooHide = true;
      }

      if (!data.survey_type) data.survey_type = this._parent._parent.getType();
      data.readonly = !!this._readonly;
      var html = template(data);

      this.$('.relationship-group').append(html);

    },
    deleteRelationship: function(e) {
      var $target = $(e.target);
      $target.closest('.box_list').remove();

      // trigger...
      this.refreshRelations();

      this.updateRelationView();
    },
    relationOptionChanged: function(e) {
      // update siblings
      var $target = $(e.target),
          $option = $target.closest('.box_list');
      var value = $target.val();

      if (value == -1) {
        // Any Option - remove other options
        $option.siblings().remove();

        this.model.set('direct', 1, {silent: true});
        this.model.set('direct_id', $option.find('.relation2').val(), {silent: true});
        // hide add relationship button
        this.$('.relationship-add').closest('.choice_box').hide();
      } else {
        this.model.set('direct', 0, {silent: true});
        this.model.unset('direct_id', {silent: true});
        // show add relationship button
        this.$('.relationship-add').closest('.choice_box').show();
      }
      this.refreshRelations();
      this.updateRelationView();
    },
    relatedOptionChanged: function(e) {
      if (this.model.get('direct') == 1) {
        var $target = $(e.target);
        this.model.set('direct_id', $target.val(), {silent: true});
      } else {
        this.model.unset('direct_id', {silent: true});
      }
      this.refreshRelations();
    },
    updateRelationView: function(rebuild, reRender) {
      var self = this;
      if (reRender) {
        this.loadRelations();
      } else {
        if (rebuild) {
          this.$('.relationship-group').find('.box_list .relation1').each(function() {
            var selectedVal = $(this).val();
            $('option', this).remove();

            var optionStr = '<option value="">--</option><option value="-1">任意选项</option>';
            _.each(self.model.get('fields'), function(field, idx){
              optionStr += '<option value="' + (field.id ? field.id : 0) + '">' + (field.title ? fixOptionText(field.title) : '选项') + '</option>';
            });

            if (self._parent.model.get('other') == 1) {
              optionStr += '<option value="-2">其他</option>';
            }

            $(this).html(optionStr);

            $(this).val(selectedVal);
          });
        }
        var field_ids = [];
        this.$('.relationship-group').find('.box_list .relation1').each(function() {
          if ($(this).val()) field_ids.push($(this).val());
        });

        this.$('.relationship-group').find('.box_list .relation1').each(function() {
          $('option', this).each(function() {
            if (!$(this).is(':selected')) {
              var val = $(this).attr('value');
              if ($.inArray(val, field_ids) != -1) {
                $(this).hide();
              } else {
                $(this).show();
              }
            }
          });
        });
      }
    },
    refreshRelations: function() {
      var relations = [];
      this.$('.relationship-group .box_list').each(function() {
        var val1 = $('.relation1', this).val();
        var val2 = $('.relation2', this).val();
        if (val1) {
          relations.push({
            fieldId: val1,
            modelId: val2
          })
        }
      });
      this.model.set('relations', relations, {silent: true});
    },
    updateRelatedOptions: function(selected) {
      if (typeof selected == 'undefined') selected = true;
      var collection = this._parent._parent.getCollection();
      var views = this._parent._parent.getViews();
      var viewIndex = views.indexOf(this._parent);
      if (viewIndex == collection.length - 1) {
        // remove relations
        this.model.set('relations', [], {silent:true});
        this.$('.relationship-group').html('');

        if (this.model.get('relationship') == 1 || this.model.get('id') && this.model.get('relations') && this.model.get('relations').length) {
          // should show add button when relationship is clear
          this.$('.relationship-add').closest('.choice_box').show();
        }

        return;
      } else {
        var views = this._parent._parent.getViews();
        this.$('.relation2').each(function() {
          var selectedVal = $(this).val();
          var optionStr = '<option value="">--</option>';
          _.each(views, function(view, idx) {
            if (idx > 0 && idx > viewIndex) {
              var model = view.model;
              optionStr += '<option value="' + idx + '">' + (model.get('title') ? fixOptionText(model.get('title')) : '未命名') + '</option>';
            }
          });
          optionStr += '<option value="-1">直接结束问卷</option>';
          $(this).html(optionStr);
          if(selected) $(this).val(selectedVal);
        });
      }
    },
    cancelRelatedOptions: function() {
      this.updateRelatedOptions(false);
    },

    clearRelations: function() {
      this.$('.relationship-group').html('');
      this.model.set('relations', [], {silent: true});
    },

    requireAction: function(e) {
      var $target = $(e.target);
      this.model.set('required', $target.prop('checked') ? 1 : 0, {silent: true});
    },
    relationshipAction: function(e) {
      var $target = $(e.target);
      this.model.set('relationship', $target.prop('checked') ? 1 : 0, {silent: true});
      if ($target.prop('checked')) {
        this.$('.setting_box .choice_box').show();
      } else {
        this.$('.setting_box .choice_box').hide();
      }
    },
    toggleSettingArea: function(e) {
      var $target = $(e.target);
      if (!$target.hasClass('close')) $target = $target.closest('.close');
      $target.closest('.setting').find('.setting_box').fadeToggle('fast', function(){
        if ($(this).is(':visible')) {
          $target.removeClass('open').find('label').html('收起');
        } else {
          $target.addClass('open').find('label').html('展开');
        }
      });
    }
  });


  /////
  Views.DefaultPreviewView = Views.ViewBase.extend({
    viewClassName: 'DefaultPreviewView',
    defaults: {
      templateId: '#noop-template',
      copyEnabled: true,
      readonly: false,
      sortable: true, // sortable icon
      topVote: 0
    },
    events: {
      'mouseover': 'handleMouseOver',
      'mouseout': 'handleMouseOut',
      'click': 'showCreateView',
      'click a.copy': 'copyView',
      'click a.delete': 'deleteView'
    },
    initialize: function(options) {
      var opts = _.extend({}, this.defaults, options);
      this._templateId = opts.templateId;
      this._parent = opts.parent;
      this._readonly = !!opts.readonly;
      this._sortable = !!opts.sortable;
      this._copyEnabled = typeof opts.copyEnabled == 'undefined' || opts.copyEnabled;
      this._topVote = opts.topVote;
      this.bind('refresh', this.refresh);
    },
    _handleDataBeforeRender: function() {
      var data = this.model.toJSON();
      if (typeof data.predefined_value == 'undefined') data.predefined_value = '';
      if (typeof data.other == 'undefined') data.other = 0;
      if (typeof data.relationship == 'undefined') data.relationship = 0;
      data.copyEnabled = this._copyEnabled;
      data.sortable = this._sortable;
      data.survey_type = 1;
      if (this._parent && this._parent._parent && this._parent._parent.getViews) {
        var index = this._parent._parent.getViews().indexOf(this._parent);
        if (index >= 0) {
          data.viewIndex = index + 1;
        } else {
          data.viewIndex = 1;
        }

        data.survey_type = this._parent._parent.getCollection().type;
      } else {
        data.viewIndex = 1;
      }
      return data;
    },
    render: function() {
      var template = _.template(this.getTemplateText());
      var data = this._handleDataBeforeRender();
      data.readonly = !!this._readonly;
      var html = template(data);
      this.$el.html(html);

      if (this._readonly) this.$el.addClass('readonly');

      setTimeout(function() {
        window.UIselect(); // @see aaa.js
      }, 10);

      return this;
    },
    refresh: function(model) {
      this.model = model;
      this.render();
    },
    handleMouseOver: function(e) {
      if (!this._readonly) this.$('.move-handler').show();
    },
    handleMouseOut: function(e) {
      if (!this._readonly) this.$('.move-handler').hide();
    },
    showCreateView: function() {
      //if (this._readonly) return;

      if (this._parent) {
        //this._parent.trigger('createview', this.model);
        this._parent.trigger('selected', this);
      } else {
        console.log('[showCreateView] parent not found');
      }
    },
    selected: function() {
      this._parent.trigger('selected', this);
    },

    copyView: function(e) {
      e.preventDefault();
      e.stopImmediatePropagation();
      this._parent.trigger('copy', this);
    },

    deleteView: function(e) {
      e.preventDefault();
      e.stopImmediatePropagation();

      this._parent.trigger('delete', this);
    }
  });


  /*------------------- Single Choice -----------------------------*/
  Views.SingleChoiceCreateView = Views.DefaultCreateView.extend({
    viewClassName: 'SingleChoiceCreateView',
    defaults: _.defaults({
      templateId: '#single-choice-create-template',
      optionTemplateId: '#single-choice-option-template'
    }, Views.DefaultCreateView.prototype.defaults),
    events: _.extend({
      'click input:radio[name=dummyField]': 'selectOption',
      'change input:radio[name=dummyField]': 'fieldChange'
    }, Views.DefaultCreateView.prototype.events),

    inputUpdate: function(event, reRender) {
      var title = this.$('input[name=title]').val();
      var desc = this.$('textarea[name=description]').val();
      var fields = [];
      this.$('input[name=field]').each(function(i) {
        fields.push({
          id: $(this).data('id'),
          title: $(this).val(),
          checked: $(this).prev().prop('checked') ? 1 : 0,
          score: $(this).next(".score").val()
        });
      });
      var required = this.$('input[name=required]').prop('checked') ? 1 : 0;
      var other = this.$('input[name=other]').length == 1 ? 1 : 0;
      
      this.model.set({title: title, description: desc, fields: fields, required: required, other: other});

      this.updateRelationView(true, reRender);
      this._parent.trigger('input:update', this);
    },

    addOption: function(e) {
      var $target = $(e.target);
      var $dl = $target.closest('dl');
      var template = _.template(this.getTemplateText(this.defaults.optionTemplateId));
      $dl.after(template({title: ''}));
      
      // show remove icon
      $('a.delet', $dl).show();
      $dl.siblings().find('a.delet').show();

      this.inputUpdate();

      this._parent.trigger('option:add', this);
    },

    removeOption: function(e) {
      var result = true;
      if (this.removeOptionConfirm && $.isFunction(this.removeOptionConfirm)) {
        result = this.removeOptionConfirm.call(this);
      }

      if (result) {
        this._removeOption(e);
      }
    },

    _removeOption: function(e) {
      var $target = $(e.target);
      var $dl = $target.closest('dl');
      if ($dl.siblings().length == this._minOptions) {
        $dl.siblings().find('a.delet').hide();
      }
      $dl.remove();

      this.inputUpdate();
      this._parent.trigger('option:remove', this);
    },

    selectOption: function(e) {
      var $target = $(e.target);
      if ($target.prop('checked')) {
        if ($target.data('x-checked')) {
          $target.removeAttr('checked');
          $target.data('x-checked', false);
        } else {
          $target.data('x-checked', true);
        }
      }

      this.$('input:radio[name=dummyField]:not(:checked)').data('x-checked', false);

      this.inputUpdate();
    },

    fieldChange: function(e) {
      var $target = $(e.target);

    }

  });

  Views.SingleChoicePreviewView = Views.DefaultPreviewView.extend({
    viewClassName: 'SingleChoicePreviewView',
    defaults: {
      templateId: '#single-choice-preview-template'
    },
    refresh: function(model) {
      this.model = model;
      this.render();
    }
  });

  Views.SingleChoiceView = Views.TypeView.extend({
    viewClassName: 'SingleChoiceView',
    getDefaultData: function() {
      return {
        title: '',
        description: '',
        type: this._type,
        fields: [
          {id: this.getRandomId(), 'title': '', checked: 0,score:0},
          {id: this.getRandomId(), 'title': '', checked: 0,score:0},
          {id: this.getRandomId(), 'title': '', checked: 0,score:0}
        ],
        required: 1,
        other: 0,
        relationship: 0
      };
    }
  });
  /*------------------- Single Choice -----------------------------*/

  /*------------------- Multiple Choice -----------------------------*/
  Views.MultipleChoiceCreateView = Views.SingleChoiceCreateView.extend({
    viewClassName: 'MultipleChoiceCreateView',
    optionTemplate: '',
    defaults: _.defaults({
      templateId: '#multiple-choice-create-template',
      optionTemplateId: '#multiple-choice-option-create-template'
    }, Views.SingleChoiceCreateView.prototype.defaults),
    events: _.extend({
      'click input:checkbox': 'selectOptions'
    }, Views.SingleChoiceCreateView.prototype.events),

    inputUpdate: function(event, reRender) {
      var title = this.$('input[name=title]').val();
      var desc = this.$('textarea[name=description]').val();
      var fields = [];
      this.$('input[name=field]').each(function(i) {
        fields.push({
          title: $(this).val(),
          checked: $(this).prev().prop('checked') ? 1 : 0,
          score: $(this).next(".score").val()
        });
      });

      var required = this.$('input[name=required]').prop('checked') ? 1 : 0;
      var other = this.$('input[name=other]').length == 1 ? 1 : 0;

      this.model.set({title: title, description: desc, fields: fields, required: required, other: other});

      //this.updateRelationView(true, reRender)
      this._parent.trigger('input:update', this);
    },

    selectOptions: function() {
      this.inputUpdate();
    }
  });
  Views.MultipleChoicePreviewView = Views.DefaultPreviewView.extend({
    viewClassName: 'MultipleChoicePreviewView',
    //className: 'preview-item',
    defaults: {
      templateId: '#multiple-choice-preview-template'
    },
    //render: function() {
    //  var template = _.template(this.getTemplateText());
    //  var html = template(this.model.toJSON());
    //  this.$el.html(html);
    //
    //  return this;
    //},
    refresh: function(model) {
      this.model = model;
      this.render();
    }
  });
  Views.MultipleChoiceView = Views.SingleChoiceView.extend({
    viewClassName: 'MultipleChoiceView',
    defaults: _.defaults({
      type: 2
    }, Views.SingleChoiceView.prototype.defaults)
  });
  /*------------------- Multiple Choice -----------------------------*/

  /*------------------- Single Image Choice -----------------------------*/
  Views.SingleImageChoiceCreateView = Views.SingleChoiceCreateView.extend({
    viewClassName: 'SingleImageChoiceCreateView',
    defaults: _.defaults({
      templateId: '#single-image-choice-create-template',
      uploadingTemplateId: '#single-image-uploading-template',
      uploadedTemplateId: '#single-image-uploaded-template',
      supportUpload: true
    }, Views.SingleChoiceCreateView.prototype.defaults),

    render: function() {
      this._parent.$el.addClass('imgQuestion');
      Views.SingleImageChoiceCreateView.__super__.render.call(this);

      return this;
    },

    getDropZone: function() {
      return '.file-upload';
    },

    progress: function(data) {
      var progress = parseInt(data.loaded / data.total * 100, 10);
      data.context.find('.progress').css('width', progress + '%');
    },

    getNumberOfFiles: function() {
      return this.$('dl.uploading').length;
    },

    append: function(data) {
      var template = _.template(this.getTemplateText(this.defaults.uploadingTemplateId));
      var $el = $($.trim(template({
        title: data.files[0].name.split('.')[0].substr(0, 20)
      })));
      this.$('.image-choice-area').append($el);

      return $el;
    },

    uploaded: function(data) {
      var template = _.template(this.getTemplateText(this.defaults.uploadedTemplateId));
      var $el = $($.trim(template({
        id: this._parent.getRandomId(),
        title: data.files[0].name.split('.')[0].substr(0, 20),
        src: data.result.data.file_url
      })));

      data.context.replaceWith($el);

      // update model
      this.inputUpdate();

      return $el;
    },

    inputUpdate: function(event, reRender) {
      var title = this.$('input[name=title]').val();
      var desc = this.$('textarea[name=description]').val();
      var fields = [];
      var self = this;
      this.$('.image-choice-area > dl.uploaded').each(function() {
        var id = $(this).data('id');
        fields.push({
          id: id,
          title: $('input[name=field]', this).val(),
          src: $('img', this).attr('src'),
          checked: $('input:radio', this).prop('checked') ? 1 : 0,
          score:$('input[name=score]', this).val()
        });
      });

      var required = this.$('input[name=required]').prop('checked') ? 1 : 0;

      this.model.set({title: title, description: desc, fields: fields, required: required});

      this._parent.trigger('option:add', this);

      this.updateRelationView(true, reRender);
      this._parent.trigger('input:update', this);
    },

    removeOption: function(e) {
      var $target = $(e.target);
      if ($target.closest('.uploading').length) {
        var randomKey = $target.closest('.uploading').data('randomKey');
        if (randomKey && this._XHRs[randomKey]) {
          this._XHRs[randomKey].abort();

          $target.closest('.uploading').remove();
        }
      } else if ($target.closest('.uploaded').length){
        $target.closest('.uploaded').remove();

        this.inputUpdate();
      }

    },

    uploadCancelled: function() {
      console.log('upload cancelled', arguments);
    },

    validate: function() {
      Views.SingleImageChoiceCreateView.__super__.validate.call(this);

      if (!this.model.get('fields') || this.model.get('fields').length < this._minOptions) {
        this._parent.trigger('error', Views.ERROR_CODES.COUNT_NOT_MATCH, this.$el, this, '图片至少传' + this._minOptions + '张');
      }

    }

  });
  Views.SingleImageChoicePreviewView = Views.SingleChoicePreviewView.extend({
    viewClassName: 'SingleImageChoicePreviewView',
    defaults: {
      templateId: '#single-image-choice-preview-template'
    }
  });
  Views.SingleImageChoiceView = Views.SingleChoiceView.extend({
    viewClassName: 'SingleImageChoiceView',

    defaults: _.defaults({
      type: 3,
      popupClass: 'imgbox'
    }, Views.SingleChoiceView.prototype.defaults),

    getDefaultData: function() {
      return {
        title: '',
        description: '',
        type: this._type,
        fields: [],
        required: 1,
        relationship: 0
      };
    }
  });
  /*------------------- Single Image Choice -----------------------------*/

  /*------------------- Multiple Image Choice -----------------------------*/
  Views.MultipleImageChoiceCreateView = Views.SingleImageChoiceCreateView.extend({
    viewClassName: 'MultipleImageChoiceCreateView',
    defaults: _.defaults({
      templateId: '#multiple-image-choice-create-template',
      uploadingTemplateId: '#multiple-image-uploading-template',
      uploadedTemplateId: '#multiple-image-uploaded-template',
      supportUpload: true
    }, Views.SingleImageChoiceCreateView.prototype.defaults),

    events: _.extend({
      'click input:checkbox[name=dummyField]': 'checkDummyField'
    }, Views.SingleImageChoiceCreateView.prototype.events),

    checkDummyField: function() {
      this.inputUpdate();
    },

    inputUpdate: function(event, reRender) {
      var title = this.$('input[name=title]').val();
      var desc = this.$('textarea[name=description]').val();
      var fields = [];
      this.$('.image-choice-area > dl').each(function() {
        fields.push({
          title: $('input[name=field]', this).val(),
          src: $('img', this).attr('src'),
          checked: $('input:checkbox', this).prop('checked') ? 1 : 0
        });
      });

      var required = this.$('input[name=required]').prop('checked') ? 1 : 0;

      this.model.set({title: title, description: desc, fields: fields, required: required});

      this.updateRelationView(true, reRender);
      this._parent.trigger('input:update', this);
    }
  });
  Views.MultipleImageChoicePreviewView = Views.SingleChoicePreviewView.extend({
    viewClassName: 'MultipleImageChoicePreviewView',
    defaults: {
      templateId: '#multiple-image-choice-preview-template'
    }
  });
  Views.MultipleImageChoiceView = Views.MultipleChoiceView.extend({
    viewClassName: 'MultipleImageChoicePreviewView',
    defaults: _.defaults({
      type: 4,
      popupClass: 'imgbox'
    }, Views.MultipleChoiceView.prototype.defaults),
    getDefaultData: function() {
      return {
        title: '',
        description: '',
        type: this._type,
        fields: {},
        required: 1,
        relationship: 0
      };
    }
  });
  /*------------------- Multiple Image Choice -----------------------------*/

  /*------------------- Single Line -----------------------------*/
  Views.SingleLineCreateView = Views.DefaultCreateView.extend({
    viewClassName: 'SingleLineCreateView',
    defaults: _.defaults({
      templateId: '#single-line-create-template',
      'relationshipOptionId': '#relationship-input-option-template'
    }, Views.DefaultCreateView.prototype.defaults),
    inputUpdate: function() {
      var fields = [{
        predefined_value: this.$('input[name=predefined_value]').val()
      }];

      this.model.set({
        title: this.$('input[name=title]').val(),
        description: this.$('textarea[name=description]').val(),
        predefined_value: this.$('input[name=predefined_value]').val(),
        required: this.$('input[name=required]').prop('checked') ? 1 : 0,
        fields: fields
      });

      this.updateRelationView(true);
      this._parent.trigger('input:update', this);
    },
    addRelationship: function(e) {
      console.log('[SingleLineCreateView] addRelationship');
      Views.DefaultCreateView.prototype.addRelationship.call(this, e);
      // hide add relationship button
      this.$('.relationship-add').closest('.choice_box').hide();
    },
    deleteRelationship: function(e) {
      console.log('[SingleLineCreateView] deleteRelationship');
      Views.DefaultCreateView.prototype.deleteRelationship.call(this, e);
      // show add relationship button
      this.$('.relationship-add').closest('.choice_box').show();
    },
    refreshRelations: function() {
      var relations = [];
      this.$('.relationship-group .box_list').each(function() {
        var val2 = $('.relation2', this).val();
        relations.push({
            fieldId: '-1',
            modelId: val2
        });
      });
      this.model.set('relations', relations, {silent: true});
    }
  });
  Views.SingleLinePreviewView = Views.DefaultPreviewView.extend({
    viewClassName: 'SingleLinePreviewView',
    defaults: {
      templateId: '#single-line-preview-template'
    }
  });
  Views.SingleLineView = Views.TypeView.extend({
    viewClassName: 'SingleLineView',
    defaults: _.defaults({
      type: 5
    }, Views.TypeView.prototype.defaults),

    getDefaultData: function() {
      return {
        title: '',
        description: '',
        type: this._type,
        required: 1,
        fields: [
          {
            predefined_value: ''
          }
        ]
      };
    }
  });
  /*------------------- Single Line -----------------------------*/

  /*------------------- Multiple Line -----------------------------*/
  Views.MultipleLineCreateView = Views.SingleLineCreateView.extend({
    viewClassName: 'MultipleLineCreateView',
    defaults: _.defaults({
      templateId: '#multiple-line-create-template'
    }, Views.SingleLineCreateView.prototype.defaults),
    events: _.extend({
      'input textarea': 'inputUpdate'
    }, Views.SingleChoiceCreateView.prototype.events),

    inputUpdate: function() {
      var fields = [{
        predefined_value: this.$('textarea[name=predefined_value]').val()
      }];
      this.model.set({
        title: this.$('input[name=title]').val(),
        description: this.$('textarea[name=description]').val(),
        required: this.$('input[name=required]').prop('checked') ? 1 : 0,
        fields: fields
      });
    }
  });
  Views.MultipleLinePreviewView = Views.SingleLinePreviewView.extend({
    viewClassName: 'MultipleLinePreviewView',
    defaults: {
      templateId: '#multiple-line-preview-template'
    }
  });
  Views.MultipleLineView = Views.SingleLineView.extend({
    viewClassName: 'SingleLineView',
    defaults: _.defaults({
      type: 6,
      popupClass: 'single'
    }, Views.SingleLineView.prototype.defaults)
  });
  /*------------------- Multiple Line -----------------------------*/

  /*------------------- Multiple Input -----------------------------*/
  Views.MultipleInputCreateView = Views.SingleChoiceCreateView.extend({
    viewClassName: 'MultipleInputCreateView',
    defaults: {
      templateId: '#multiple-input-create-template',
      optionTemplateId: '#multiple-input-option-create-template'
    }
  });
  Views.MultipleInputPreviewView = Views.DefaultPreviewView.extend({
    viewClassName: 'MultipleInputPreviewView',
    defaults: {
      templateId: '#multiple-input-preview-template'
    }
  });
  Views.MultipleInputView = Views.TypeView.extend({
    viewClassName: 'MultipleInputCreateView',
    defaults: _.defaults({
      type: 7
    }, Views.TypeView.prototype.defaults),
    getDefaultData: function() {
      return {
        title: '',
        description: '',
        type: this._type,
        fields: [
          {title: ''},{title: ''},{title: ''}
        ],
        required: 1
      };
    }
  });
  /*------------------- Multiple Input -----------------------------*/

  /*------------------- Sorting Input -----------------------------*/
  Views.SortingCreateView = Views.SingleChoiceCreateView.extend({
    viewClassName: 'SortingCreateView',
    defaults: _.defaults({
      templateId: '#sorting-create-template',
      optionTemplateId: '#sorting-option-create-template',
      'relationshipOptionId': '#relationship-input-option-template'
    }, Views.SingleChoiceCreateView.prototype.defaults),
    addRelationship: function(e) {
      console.log('[SortingCreateView] addRelationship');
      Views.DefaultCreateView.prototype.addRelationship.call(this, e);
      // hide add relationship button
      this.$('.relationship-add').closest('.choice_box').hide();
    },
    deleteRelationship: function(e) {
      console.log('[SortingCreateView] deleteRelationship');
      Views.DefaultCreateView.prototype.deleteRelationship.call(this, e);
      // show add relationship button
      this.$('.relationship-add').closest('.choice_box').show();
    },
    refreshRelations: function() {
      var relations = [];
      this.$('.relationship-group .box_list').each(function() {
        var val2 = $('.relation2', this).val();
        relations.push({
          fieldId: '-1',
          modelId: val2
        });
      });
      this.model.set('relations', relations, {silent: true});
    }
  });
  Views.SortingPreviewView = Views.DefaultPreviewView.extend({
    viewClassName: 'SortingPreviewView',
    defaults: {
      templateId: '#sorting-preview-template'
    }
  });
  Views.SortingView = Views.TypeView.extend({
    viewClassName: 'SortingView',
    defaults: _.defaults({
      type: 8
    }, Views.TypeView.prototype.defaults),
    getDefaultData: function() {
      return {
        title: '',
        description: '',
        type: this._type,
        fields: [
          {title: ''},{title: ''},{title: ''}
        ],
        required: 1
      };
    }
  });
  /*------------------- Sorting Input -----------------------------*/

  /*------------------- Promotion -----------------------------*/
  Views.PromotionCreateView = Views.DefaultCreateView.extend({
    viewClassName: 'PromotionCreateView',
    defaults: {
      templateId: '#promotion-create-template'
    },
    inputUpdate: function() {
      var title = this.$('input[name=title]').val();
      var desc = this.$('textarea[name=description]').val();
      var required = this.$('input[name=required]').prop('checked') ? 1 : 0;

      this.model.set({title: title, description: desc, required: required});
    },

    validate: function() {
      Views.PromotionCreateView.__super__.validate.call(this);

      console.log('promotion validate');
      var $el = this.$el.closest('.question').find('.select');
      var val = $('.bar', $el).text();
      if (!val.match(/^\d+$/)) {
        this._parent.trigger('error', Views.ERROR_CODES.COUNT_NOT_MATCH, $el, this);
        $el.addClass('invalid');
      }
    }
  });
  Views.PromotionPreviewView = Views.DefaultPreviewView.extend({
    viewClassName: 'PromotionPreviewView',
    defaults: {
      templateId: '#promotion-preview-template',
      copyEnabled: false
    },
    _handleDataBeforeRender: function() {
      var data =  Views.DefaultPreviewView.prototype._handleDataBeforeRender.call(this);
      data.topVote = this._parent._topVote;
      data.selectTopVote = this._parent._selectedTopVote;
      return data;
    }
  });
  Views.PromotionView = Views.TypeView.extend({
    viewClassName: 'PromotionView',
    defaults: _.defaults({
      type: 14,
      relatedIndex: 1,
      sortable: false
    }, Views.TypeView.prototype.defaults),
    initialize: function(options) {
      this._selectedTopVote = options.selectedTopVote ? options.selectedTopVote : 0;
      this._relatedIndex = options.relatedIndex;

      Views.TypeView.prototype.initialize.call(this, options);
    },
    getDefaultData: function() {
      return {
        title: '',
        description: '',
        type: this._type,
        fields: [],
        required: false,
        relatedIndex: this._relatedIndex
      };
    },
    getData: function() {
      var viewData = {};
      if (this.model) {
        viewData = this.model.toJSON();
        viewData.top_vote = this.getSelectTopVote();
      }
      return viewData;
    },
    getSelectTopVote: function() {
      return this._selectedTopVote;
    },
    setSelectTopVote: function(count) {
      this._selectedTopVote = count;
      this.model.set('top_vote', count);
    },
    getTopVote: function() {
      return this._topVote;
    },
    setTopVote: function(count) {
      this._topVote = count;
    }
  });
  /*------------------- Promotion -----------------------------*/
  /////////////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////////////

  // Step 1 view
  Views.FirstStepView = Views.ViewBase.extend({
    viewClassName: 'FirstStepView',
    defaults: {
      templateId: '#survey-step-1'
    },
    events: {
      'focus input': 'focusAction',
      'input #survey_name': 'titleChange',
      'click .survey-type': 'typeChange',
      'change input:radio[name=privacy]': 'privacyChange',
      'change input:radio[name=is_score]': 'is_scoreChange',
      'change input:radio[name=is_result]': 'is_resultChange',
      'click #survey-step-1-create': 'createSurvey'
    },
    initialize: function(options) {
      Views.ViewBase.prototype.initialize.call(this, options);
    },
    didInsertElement: function() {
      if (this.model.get('type') != 1) {
        // select Type icon
        var $el = this.$('.survey-type[data-type=' + this.model.get('type') + ']');
        $el.siblings().removeClass('active').end().addClass('active');
        this.$('.survey-hint').html($el.data('hint'));
      }

      var self = this;
      this.$('input.start-time').datetimepicker({
        format: 'Y-m-d H:i',
        formatDate:'Y-m-d H:i',
        //timepicker: false,
        onShow: function(ct) {
          this.setOptions({
            minDate: '-1970-01-01 00:00',
            maxDate: self.$('input.end-time').val() ? self.$('input.end-time').val() : false
          })
        },
        onChangeDateTime: function(ct, $i) {
          self.model.set('start_time', ct.format('yyyy-MM-dd hh:mm'));
        }
      });

      this.$('input.end-time').datetimepicker({
        format: 'Y-m-d H:i',
        formatDate:'Y-m-d H:i',
        //timepicker: false,
        onShow: function(ct) {
          this.setOptions({
            minDate: self.$('input.start-time').val() ? self.$('input.start-time').val() : false
          });
        },
        onChangeDateTime: function(ct, $i) {
          self.model.set('end_time', ct.format('yyyy-MM-dd hh:mm'));
        }
      });
    },
    validate: function() {
      var hasError = false;
      var title = this.model.get('title'),
        start_time = this.model.get('start_time'),
        end_time = this.model.get('end_time');

      if (!title) {
        this.$('#survey_name').addClass('invalid').next().attr('title', '必填项');
        hasError = true;
      }
      else if (!this.isValidText(title)) {
        this.$('#survey_name').addClass('invalid').next().attr('title', '包含非法字符<>/%!=');
        hasError = true;
      }

      if (!start_time) {
        this.$('.start-time').addClass('invalid').next().attr('title', '必填项');
        hasError = true;
      }
      if (!end_time) {
        this.$('.end-time').addClass('invalid').next().attr('title', '必填项');
        hasError = true;
      }

      if (start_time) start_time = moment(start_time, "YYYY-MM-DD HH:mm");
      if (end_time) end_time = moment(end_time, "YYYY-MM-DD HH:mm");

      var startDatetime = new Date(start_time);
      var endDatetime = new Date(end_time);

      if (start_time && !this.isValidDate(startDatetime)) {
        this.$('.start-time').addClass('invalid').next().attr('title', '日期格式有误');
        hasError = true;
      }
      if (end_time && !this.isValidDate(endDatetime)) {
        this.$('.end-time').addClass('invalid').next().attr('title', '日期格式有误');
        hasError = true;
      }

      // check start - end
      if (startDatetime.getTime() >= endDatetime.getTime()) {
        this.$('.start-time, .end-time').addClass('invalid').next().attr('title', '开始时间必须晚于结束时间');
        hasError = true;
      }

      return !hasError;
    },
    getData: function() {
      var data = this.model.toJSON();
      return data;
    },
    focusAction: function(e) {
      $(e.currentTarget).removeClass('invalid').removeAttr('title');
    },
    titleChange: function() {
      this.model.set('title', this.$('#survey_name').val());
    },
    typeChange: function(e) {
      var $target = $(e.currentTarget);
      if ($target.closest('.chose').hasClass('readonly')) return;

      $target.siblings().removeClass('active').end().addClass('active');
      var type = $target.data('type');
      if(type==1){
    	  $(".pingfen").show();
      }else{
    	  $("._score1").click();
    	  $(".pingfen").hide();
      }
      this.model.set('type', type);

      this.$('.survey-hint').html($target.data('hint'));
    },
    privacyChange: function(e) {
      var privacy = this.$('input:radio[name=privacy]:checked').val();
      this.model.set('privacy', privacy);
    },
    is_scoreChange: function(e) {
        var is_score = this.$('input:radio[name=is_score]:checked').val();
        console.log(is_score);
        this.model.set('is_score', is_score);
    },
    is_resultChange: function(e) {
    	var is_result = this.$('input:radio[name=is_result]:checked').val();
        console.log(is_result);
        this.model.set('is_result', is_result);
    },
    isValidDate: function(d) {
      if ( Object.prototype.toString.call(d) === "[object Date]" ) {
        // it is a date
        if ( isNaN( d.getTime() ) ) {  // d.valueOf() could also work
          // date is not valid
          return false;
        }
        else {
          // date is valid
          return true;
        }
      }
      else {
        // not a date
        return false;
      }
    },
    createSurvey: function() {

      if (!this.validate()) {
        return;
      }

      var self = this;
      var data = this.model.toJSON();

      var publishedRest = false;
      if (data.published == 1 && data.answer_count == 0 && data.type != Views.SURVEY_TYPES.PROMOTION) {
        publishedRest = true;
      }

      if (this.model.survey_id) {
        this.model.fetch({
          url: '/survey/basic.do',
          type: 'POST',
          data: {survey_data: JSON.stringify(data)},
          success: function(coll, response) {
            if (response && response.status == 1) {
              if (publishedRest) {
                alert('更新成功，请重新发布该问卷');
              } else {
                alert('更新成功');
              }
              if (self._parent) self._parent.saveSuccess(self.model, 'edit');
            } else {
              alert('更新失败');
            }
          }
        });
      } else {
        this.model.fetch({
          url: '/survey/create.do',
          type: 'POST',
          data: {survey_data: JSON.stringify(data)},
          success: function(coll, response) {
            if (response && response.status == 1 && response.data && response.data.id) {
              self.model.survey_id = response.data.id;
              alert('保存成功');
              if (self._parent) self._parent.saveSuccess(self.model, 'new');
            } else {
              alert('保存失败');
            }
          }
        });
      }
    }
  });

  $.extend({
    SurveyMaxQuestion: 100,
    SurveyFirstStep: function(options) {

      var $container = $(options.container);

      var data = $.extend({}, {
          title: '',
          type: 1,
          start_time: '',
          end_time: '',
          privacy: 2,
          is_score: 0,
          is_result: 1,
          event_id: getQueryString('event_id'),
          survey_id: getQueryString('survey_id')
        }, options.data);

      return {
        init: function() {
          var model = new Backbone.Model(data, {parse: true});
          if(getQueryString('survey_id')) model.survey_id = getQueryString('survey_id');
          var view = new Views.FirstStepView({
            model: model,
            parent: this
          });
          view.render();

          $container.html(view.el);

          view.didInsertElement();
          return this;
        },
        show: function() {
          $container.show();
          return this;
        },
        hide: function() {
          $container.show();
          return this;
        },
        saveSuccess: function(model, mode) {
          if ($.isFunction(options.saveSuccess)) options.saveSuccess.call(this, model, mode);
        },
        saveFail: function() {}
      };
    },

    SurveyView: function(options) {
      var MAX_QUESTIONS = 100;
      var defaults = {
        surveyType: 1,
        max: $.SurveyMaxQuestion,
        data: {
          title: '',
          description: '',
          type: 0,
          is_score:0,
          is_result:1
        },
        readonly: false,
        sortable: true
      };
      options = $.extend({}, defaults, options);

      var _max = options.max;

      var $container = $(options.container);
      //var $createContainer = $(options.createContainer);
      var $previewContainer = $('.questions', $container);

      var _views = [], _curView = null;

      var models = options.data.models ? options.data.models : [];
      var collection = new SurveyCollection(models, {
        title: options.data.title,
        description: options.data.description,
        type: options.data.type,
        is_score:options.data.is_score,
        is_result:options.data.is_result
      });

      function updateViewIndex() {
        $('.model-index', $previewContainer).each(function(index) {
          $(this).html((index + 1) + '.');
        });
      }

      function isRelated(index) {
        var result = false;
        _.each(_views, function(view, idx) {
          if (!result && view.isRelated(index)) {
            result = true;
          }
        });
        return result;
      }

      function hasRelated(index) {
        var view = _views[index];
        if (view) {
          return view.hasRelated();
        }
        return false;
      }

      function cancelRelatedOptions(index) {
        _.each(_views, function(view, idx) {
          view.cancelRelatedOptions();
        });
      }

      function clearRelations(index) {
        var view = _views[index];
        if (view) view.clearRelations();
      }

      function updateRelatedOptions() {
        _.each(_views, function(view, idx) {
          view.updateRelatedOptions();
        });
      }

      var startIndex = -1,
        isPreActive = false,
        isRelatedChange = false,
        isClearRelations = false;
      //var movedView = null;
      if (!options.readonly && options.sortable) {
        $previewContainer.sortable({
          cancel: ".disabled",
          handle: ".move-handler",
          start: function(e, ui) {
            isRelatedChange = isClearRelations = false;
            console.log('start', ui.item.index());
            startIndex = ui.item.index();
            //var keys = _.keys(_views);
            //movedView = _views[keys[startIndex]];
            isPreActive = ui.item.hasClass('active');
            if (isPreActive) {
              ui.item.removeClass('active');
            }
          },
          beforeStop: function(e, ui) {
            console.log('beforeStop', ui.item.index());
            if (isRelated(startIndex)) {
              if (confirm('该问题已被关联，更改位置将取消关联, 确定？')) {
                isRelatedChange = true;
              } else {
                $(this).sortable('cancel');
              }
            } else if (ui.item.index() == $previewContainer.find('.row-item').length - 2 && hasRelated(startIndex)) { // the template item exists, we should minus 2
              if (confirm('移动此问题将取消关联, 确定？')) {
                isRelatedChange = true;
              } else {
                $(this).sortable('cancel');
              }
            } else if (startIndex == $previewContainer.find('.row-item').length - 2 && hasRelated(ui.item.index())) {
              if (confirm('移动此问题将取消关联, 确定？')) {
                isClearRelations = true;
              } else {
                $(this).sortable('cancel');
              }
            }
          },
          update: function(e, ui) {
            console.log('update', ui.item.index());
            if (startIndex != -1) {
              // update the positions of views
              _views.splice(ui.item.index(), 0, _views.splice(startIndex, 1)[0]);

              // update collection models
              collection.models.splice(ui.item.index(), 0, collection.models.splice(startIndex, 1)[0]);
              //console.log(collection.toJSON());
            }

            updateViewIndex();

            updateRelatedOptions();
          },
          stop: function(e, ui) {
            console.log('stop', ui.item.index());
            if (isPreActive) {
              _views[ui.item.index()].trigger('selected');
              //ui.item.addClass('active');
            }

            if (isRelatedChange) cancelRelatedOptions();
            if (isClearRelations || ui.item.index() == $previewContainer.find('.row-item').length - 1) clearRelations(ui.item.index());
          }
        });
      }

      var hasError = false;
      var errors = [];

      return {
        getCollection: function() {
          return collection;
        },
        getViews: function() {
          return _views;
        },
        setId: function(id) {
          collection.survey_id = id;
        },
        handleError: function(code, element, view, message) {
          errors.push({code: code, element: element, view: view, message: message});
        },
        handleAddOption: function(view) {
          if (options.surveyType == Views.SURVEY_TYPES.PROMOTION) {
            this.updateTopVote();
          }
        },
        handleRemoveOption: function(view) {
          if (options.surveyType == Views.SURVEY_TYPES.PROMOTION) {
            this.updateTopVote('remove');
          }
        },
        getData: function() {
          errors = [];

          var data = {
            title: collection.title,
            description: collection.description,
            type: collection.type,
            models: []
          };
          $.each(_views, function(idx, view) {
            if (view.$el.is(':visible')) {
              view.validate();
              var viewData = view.getData();
              data.models.push(viewData);
            }
          });
          return data;
        },
        setTitle: function(title) {
          collection.title = title;
        },
        setDescription: function(description) {
          collection.description = description;
        },
        setType: function(type) {
          collection.type = type;
        },
        getType: function() {
          return collection.type;
        },
        addModel: function(model, index) {
          //console.log('[addModel] add index:', index);
          if (typeof index != 'undefined' && index < collection.length) {
            collection.add(model, {at: index});
          } else {
            collection.add(model);
          }
        },
        renderViews: function() {
          var self = this;
          if (models) {
            if (options.surveyType == 3) {
              if (models.length > 0) {
                var model0 = models[0];
                var type = model0.type;
                self.addView(type, new SurveyModel(model0, {parse: true}));

                for(var i = 1; i < models.length; i++) {
                  models[i].relatedIndex = i;
                  self.addPromotionView(new SurveyModel(models[i], {parse: true}), models[i].top_vote, false);
                }
              }
            } else {
              $.each(models, function(idx, model) {
                var type = model.type;
                self.addView(type, new SurveyModel(model, {parse: true}));
              });
            }
          }
        },
        addView: function(type, model, index) {

          if (_views.length >= _max) {
            alert('题目数量超过上限');
            return;
          }

          if (_curView) _curView.unselect();

          var viewClass = Views[Views.QUESTION_TYPES[type] + 'View'];
          if (!viewClass) {
            throw Views.QUESTION_TYPES[type] + 'View Not defined';
          }

          var opt = {parent: this};
          var isActive = true;
          if (model) {
            opt['model'] = model;
            opt['active'] = false;
            isActive = false;
          }
          if (options.readonly) {
            opt['readonly'] = true;
          }

          opt['sortable'] = options.sortable;

          if (options.surveyType == Views.SURVEY_TYPES.PROMOTION) {
            opt['copyEnabled'] = false;
            opt['minOptions'] = 3;
            opt['onRemoveOption'] = function(view) {
              var nextView = _views[1];
              var topVote;
              if (nextView) {
                topVote = parseInt(nextView.model.get('top_vote'));
                if (isNaN(topVote)) topVote = 0;
              }
              if (topVote && view.model.get('fields').length <= topVote + 1) {
                if (confirm('删除该选项将重新设置依赖关系，继续？')) {
                  return true;
                }
                return false;
              }
              return true;
            }
          }

          var view = new viewClass(opt);
          view.render();

          _curView = view;

          if (typeof index != 'undefined' && index < _views.length) {
            _views.splice(index, 0, view);
            this.addModel(view.model, index);

            $previewContainer.find('.question').eq(index).before(view.el);
          } else {
            _views.push(view);
            this.addModel(view.model);

            $previewContainer.append(view.el);
          }

          this.updateViewIndex();

          //if (collection.type == 4 && _views.indexOf(_curView) === 0) {
          //  view.$el.addClass('disabled');
          //}
          if (options.surveyType == Views.SURVEY_TYPES.MICRO) updateRelatedOptions();

          if (isActive) {
            _curView.trigger('selected');
          }

          if (options.viewAdded && $.isFunction(options.viewAdded)) {
            return options.viewAdded.apply(this, [view, _views]);
          }
        },
        addPromotionView: function(model, selectedTopVote, active) {
          console.log('promotion view adding...');
          if (typeof active == 'undefined') active = true;

          if (_views.length == 0) return;

          if (_curView) _curView.unselect();

          var topVote = _views[0].model.has('fields') ? _views[0].model.get('fields').length : 0;
          if (_views.length > 1) {
            var promotionView = _views[_views.length - 1];
            if (promotionView instanceof Views.PromotionView) {
              topVote = promotionView.getSelectTopVote();
            }
          }

          var opt = {parent: this, topVote: topVote, relatedIndex: _views.length, active: active};

          if (options.readonly) opt['readonly'] = true;
          if (model) opt['model'] = model;
          if (selectedTopVote) opt['selectedTopVote'] = selectedTopVote;

          var view = new Views.PromotionView(opt);
          view.render();
          _curView = view;

          _views.push(view);
          this.addModel(view.model);

          $previewContainer.append(view.el);

          this.updateViewIndex();
          if (options.viewAdded && $.isFunction(options.viewAdded)) {
            return options.viewAdded.apply(this, [view, _views]);
          }
        },
        updatePromotionView: function($item) {
          if (_curView && _curView instanceof Views.PromotionView) {
            var curTopVote = _curView.getSelectTopVote();
            var count = $item.text();

            if (curTopVote == count) return;
            _curView.setSelectTopVote(count);

            // check field count of next all promotion views
            var index = _views.indexOf(_curView);
            if (index != -1 && index < _views.length - 1) {
              var nextView = _views[index + 1];
              var nextTopVote = nextView.getSelectTopVote();
              if (nextTopVote > count || count == 2) {
                // remove all next views
                nextView.$el.nextAll().find('a.delet').trigger('click');
                nextView.$('a.delet').trigger('click');
              } else {
                // update field count of all next views
                for(var i = index + 1; i < _views.length; i++) {
                  var thisView = _views[i];
                  thisView.setTopVote(count);
                  if (thisView.getSelectTopVote() == count) {
                    thisView._selectedTopVote = 0;
                  }
                  thisView._active = false;
                  thisView.render();
                }
              }
            }
          }
        },
        updateTopVote: function(method) {
          if (_views.length > 1) {
            var view0 = _views[0];
            var fieldCount = view0.model.get('fields').length;

            var view1 = _views[1];
            var topVote = view1.getSelectTopVote();
            view1.setTopVote(fieldCount);
            view1._active = false;
            if (topVote >= fieldCount) {
              view1._selectedTopVote = 0;

              // remove other promotion views
              for(var i = 2; i < _views.length; i++) {
                var _view = _views[i];
                _view.$('a.delet').trigger('click');
              }
            }
            view1.render();
          }
        },
        removeView: function(view) {
          if (_curView) _curView.unselect();
          var index = _views.indexOf(view);
          if (index >= 0) {
            this.removeModel(view.model);
            _views.splice(index, 1);

            this.updateViewIndex();

            if (view instanceof Views.PromotionView) {
              console.log('current view is PromostionView');
              // new current view
              var curView = _views[index];
              if (curView) {
                // remove next siblings views
                var $nextViews = curView.$el.nextAll();
                $nextViews.find('a.delet').trigger('click');

                curView.$('a.delet').trigger('click');
              }
            } else {
              // check next view
              var curView = _views[index];
              if (curView && curView instanceof Views.PromotionView) {
                // remove all promotion views
                curView.$el.nextAll().find('a.delet').trigger('click');
                curView.$('a.delet').trigger('click');
              }
            }
          }


        },
        inputUpdated: function(view) {
          var index = _views.indexOf(view);
          //if (isRelated(index)) {
            // update all relations
            updateRelatedOptions();
          //}
        },
        isReadonly: function() {
          return options.readonly;
        },
        selected: function(view) {
          //console.log('view selected', view);
          _curView = view;
          if (options.selected && $.isFunction(options.selected)) {
            return options.selected.apply(this, [view]);
          }
        },
        getCurrentSelectedModel: function() {
          if (_curView) {
            return _curView.model;
          }
          return null;
        },
        preview: function() {

          $('.survey-form-preview-container .form-title').html(collection.title);
          $('.survey-form-preview-container .form-description').html(collection.description);

          if (_views.length) {
            var view, $el;
            for(var i = 0; i < _views.length; i++) {
              view = _views[i];
              $el = $(view.preview()).clone().find('input,textarea').removeAttr('disabled').removeAttr('readonly').end();
              $('.survey-form-preview-content fieldset').append($el);
            }

            $('.survey-form-preview-container').show();
          }
        },

        copyView: function(view) {
          var viewType = view._type;
          var index = _views.indexOf(view);
          if (index >= 0) {
            // copy the model
            var newModel = view.model.clone();

            this.addView(viewType, newModel, index + 1);
          }
        },

        removeModel: function(model) {
          collection.remove(model);
          if (options.viewRemoved && $.isFunction(options.viewRemoved)) {
            return options.viewRemoved.apply(this, [model]);
          }
        },

        save: function(event_id) {

          if (_views.length > _max) {
            alert('题目数量超过上限');
            return;
          }

          var data = this.getData();
          data.event_id = event_id;

          if (errors.length > 0) {
            // show error view if not shown
            if ($container.find('.question').length != 0) {
              // active view
              $container.find('.question.active').removeClass('active');

              // show the first error view
              var view = errors[0].view;
              //view.$el.closest('.question').addClass('active');
              view._parent.trigger('selected'); // select the question
              if (errors[0].message) {
                alert(errors[0].message);
              }
            }
            return;
          }
          
          var publishedRest = false;
          if (options.data && options.data.published == 1 && data.type != Views.SURVEY_TYPES.PROMOTION) {
            publishedRest = true;
          }

          if (collection.survey_id) {
            data.survey_id = collection.survey_id;
            collection.fetch({
              url: '/survey/update.do',
              type: 'POST',
              data: {survey_data: JSON.stringify(data)},
              success: function(coll, response) {
                if (response && response.status == 1) {
                  if (publishedRest) alert('更新成功，请重新发布该问卷');
                  location.href = '/html/page/survey/list.html?event_id=' + event_id;
                } else {
                  alert('更新失败');
                }
              }
            });
          } else {
            collection.fetch({
              url: '/survey/create.do',
              type: 'POST',
              //contentType: 'application/json; charset=utf8',
              data: {survey_data: JSON.stringify(data)},
              success: function(coll, response) {
                if (response && response.status == 1 && response.data && response.data.id) {
                  collection.survey_id = response.data.id;
                  alert('保存成功');
                  location.href = '/html/page/survey/list.html?event_id=' + event_id;
                } else {
                  alert('保存失败');
                }
              }
            });
          }
        },

        updateViewIndex: function() {
          updateViewIndex();
        },

        isRelated: function(view) {
          var index = _views.indexOf(view);
          if (index >= 0) {
            return isRelated(index);
          }
          return false;
        },

        updateRelatedOptions: function() {
          updateRelatedOptions();
        },

        clearRelations: function(index) {
          clearRelations(index);
        }

      };
    }
  });

////////////////////////////////////////////////////////////////////////////
  if(getQueryString('survey_id')) {
    document.title = '编辑调查问卷';
  }
  $(document).ready(function() {
    var event_id = getQueryString("event_id");
    var survey_id = getQueryString('survey_id');

    var $cur_opt = null;
    var title = '', description = '';
    var type = Views.SURVEY_TYPES.MICRO;
    var $surveyView = null;

    function validateSurveyHead() {
      var hasError = false;
      $('.box_title input:text, textarea').each(function() {
        var value = $(this).val(),
          required = $(this).prop('required'),
          pattern = $(this).prop('pattern'),
          maxlength = $(this).prop('maxlength');
        if (required && $.trim(value).length == 0) {
          $(this).addClass('invalid').next().attr('title', '必填项');
          hasError = true;
        } else if ($.trim(value).length > 0 && pattern) {
          var regExp = new RegExp(pattern);
          if (!value.match(regExp) || value.match(regExp)[0] != value) {
            $(this).addClass('invalid').parent().find(".invalid").attr('title', '存在非法字符<>\/%!=或评分不为正整数');
            hasError = true;
          }
        } else if (maxlength > 0 && $.trim(value).length > maxlength && $(this).is('textarea')) {
          $(this).addClass('invalid').next().attr('title', '超过最大长度100');
          hasError = true;
        }

        if (!hasError) $(this).removeClass('invalid').next().removeAttr('title');

      });
      return !hasError;
    }

    function showSurveyHead() {
      if ($('.box_title').closest('.survey_details').hasClass('readonly')) return;

      $('.box_title').hide();
      $('.box_title:not(.end)').show();

      $('.question.active').removeClass('active');

    }

    function hideSurveyHead() {
      var title = $('.box_title input[name=title]').val();
      var description = $('.box_title textarea[name=description]').val();
      $('.box_title').hide();
      $('.box_title.end h2').html(_.escape(title) ? _.escape(title) : '未命名标题');
      $('.box_title.end p').html(_.escape(description));
      $('.box_title.end').show();
    }

    function gotoStep2(survey) {

      title = survey.title;
      description = survey.description;
      type = survey.type;

      var template = _.template($('#survey-step-2').html());
      $('.survey_details').find('.content').html(template(survey)).end().delay(500).show('blind');
      $('.survey-options').hide();

      $('.box_title input[name=title]').val(title ? title : '未命名标题');
      $('.box_title textarea[name=description]').val(description);

      var readonly = (survey.survey_status == 0 ||  survey.answer_count > 0 || survey.type == Views.SURVEY_TYPES.PROMOTION && survey.published == 1 && !survey.first_step);
      $surveyView = $.SurveyView({
        surveyType: type,
        max: type == Views.SURVEY_TYPES.SINGLE ? 1 : $.SurveyMaxQuestion,
        readonly: readonly,
        sortable: survey.type !=  Views.SURVEY_TYPES.PROMOTION,
        data: survey,
        container: '.survey_details .content',
        selected: function(view) {
          if (this.isReadonly()) return;

          // hide survey title/description
          title = $('.box_title input[name=title]').val();
          description = $('.box_title textarea[name=description]').val();

          if (!validateSurveyHead()) return false;

          hideSurveyHead();

          $surveyView.setTitle(title);
          $surveyView.setDescription(description);

          $('.survey-options').hide();
          $('.survey-add-option').parent().show();
        },
        viewAdded: function(view, views) {
          //console.log('view added', type, view, views);
        },
        viewRemoved: function(model) {
          //console.log('view removed', model);
        }
      });
      $surveyView.setId(survey_id);
      $surveyView.setType(type);
      $surveyView.renderViews();
//      setTimeout(function(){alignH();},1000);
      if (readonly) {
        $('.choose').hide();
      }

      // Can NOT edit the survey when survey is submitted or deleted
      if (readonly) {
        $('.survey_details').addClass('readonly');

        hideSurveyHead();

        $('#survey-step-2-create').hide();

        $('.survey-add-option').parent().hide();
      }

      window.$surveyView = $surveyView;
    }

    if (survey_id) {
      if (location.hash != '#config') {
        $('.global_leftMenu').parent().hide('slide', {direction: 'left'}, 600);
      }

      //$('.survey_details').show();
      $.get('/survey/admin/view.do', {event_id: event_id, survey_id: survey_id}, function(result) {
        $('.loading').hide();
        if (result && result.data && result.data.survey) {
          var survey = result.data.survey;
          $("#is_not_score").val(survey.is_score);
          $("#is_not_result").val(survey.is_result);
          if (location.hash == '#config') {
            $('.survey_details').hide();

            $.SurveyFirstStep({
              container: '.create_survey',
              data: survey,
              saveSuccess: function(model, mode) {
                if (mode == 'new') {
                  // goto step 2
                  location.href = '/html/page/survey/create.html?event_id=' + event_id + '&survey_id=' + model.survey_id;
                } else {
                  // goto list
                  location.href = '/html/page/survey/list.html?event_id=' + event_id;
                }
              }
            }).init().show();
          } else {
            gotoStep2(survey);
          }
        } else {
          if (result.status == 3 && result.data) {
            if (result.data.errorCode == 2) {
              alert('您无权限查看此问卷');
            }
          } else {
            alert(result.msg);
          }
          location.href = '/html/page/survey/list.html?event_id=' + event_id;
        }
      });

    } else {
      $('.survey_details, .loading').hide();
      $.SurveyFirstStep({
        container: '.create_survey',
        saveSuccess: function(model, mode) {
          if (mode == 'new') {
            // goto step 2
            location.href = '/html/page/survey/create.html?event_id=' + event_id + '&survey_id=' + model.survey_id;
          } else {
            // goto list
            location.href = '/html/page/survey/list.html?event_id=' + event_id;
          }
        }
      }).init().show();

    }

    ///////////////////////////////////////////////////////////////// Events
    //$('.create_survey').on('click', '.survey-type', function(e) {
    //  // select survey type
    //  $(this).siblings().removeClass('active').find('b').hide().end().end().find('b').show().end().addClass('active');
    //
    //  // update hint
    //  $('.survey-hint').html($(this).data('hint'));
    //});

    $('.content').on('click', '.survey-add-option', function(e) {
      // don't hide it when this survey is a promotion survey
      if (type == Views.SURVEY_TYPES.PROMOTION && $surveyView && $surveyView.getCollection().length > 0) {
        var views = $surveyView.getViews();
        if (views && views.length > 0) {
          var lastView = views[views.length - 1];
          if (lastView instanceof Views.PromotionView) {
            var topVote = lastView.getSelectTopVote();
            if (topVote && topVote == 2) {
              alert('无法添加，题目至少保留两个选项');
              return;
            }
          }
        }
        $surveyView.addPromotionView();
        return;
      }
      $(this).parent().hide();
      $('.survey-options').show().focus();
    }).on('blur', '.survey-options', function(){
      $(this).hide();
      $('.survey-add-option').parent().show();
    }).on('click', '.survey-option', function(e) {

      if (!validateSurveyHead()) return false;

      title = $('.box_title input[name=title]').val();
      description = $('.box_title textarea[name=description]').val();

      hideSurveyHead();

      $surveyView.setTitle(title);
      $surveyView.setDescription(description);
      //$surveyView.setType(type);
      $surveyView.addView($(this).data('type'));

      $('.survey-add-option').parent().show();
      $('.survey-options').hide();

    }).on('input', '#survey_description', function() {
      if ($surveyView) $surveyView.setDescription($(this).val());
    }).on('click', '#survey-step-2-create', function() {
      title = $('.box_title input[name=title]').val();
      description = $('.box_title textarea[name=description]').val();

      if (!validateSurveyHead()) return false;

      if ($surveyView) {
        $surveyView.setTitle(title);
        $surveyView.setDescription(description);
        $surveyView.save(event_id);
      }

    }).on('click', '#survey-preview', function() {
      if ($surveyView) $surveyView.preview();
      $('.global_form.global_right').show();
    }).on('click', '.box_title.end', function(e) {
      // can NOT edit
      if ($(this).closest('.survey_details').hasClass('readonly')) return;

      showSurveyHead();
    });

    $('.survey-form-preview-container').on('click', '.btnBack', function(e) {
      $('.survey-form-preview-container').find('fieldset').html('').end().hide();
    });


  });

})(jQuery);

function alignH() {    
    var $outer = $(".details .imgQuestion ul");
    //拼装原始高度数组
    $outer.each(function(m){    	
		var $items = $(this).find("p");    
		var rowNum = parseInt( $(this).width() / $items.width() );
		var itemsH = $items.height();
		var $itemsInner = $items.find("span");
		var arr = [];
		var arrNew = [];
		var i=0;    	    
    	$itemsInner.each(function (n) {
            if ( n%rowNum == 0 ) {
                arr[i] = [];
            }
            arr[i].push($(this).height());
            if ( arr[i].length == rowNum ) {
                i++;
            }            
        });
    	
    	//整理高度数组值
        for ( var k=0; k<arr.length; k++ ) {
            
            for ( var l=0; l<arr[k].length; l++ ) {
                var onOff = false;
                if ( arr[k][l] > itemsH ) {
                    onOff = true;
                    break;
                }
            }
            if ( onOff ) {
                for ( var m=0; m<arr[k].length; m++ ) {
                    arr[k][m] = itemsH*2;
                }
            }
            
        }
        
        //整理为新结构数组
        for ( var k=0; k<arr.length; k++ ) {
            for ( var l=0; l<arr[k].length; l++ ) {
                arrNew.push(arr[k][l]);
            }
        }
        
        //为各项赋值
        for ( var i=0; i<$items.length; i++ ) {
            $items.eq(i).height(arrNew[i]);
        }
    });
}